package com.sc.VenusQueryBeta.ui.activites.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.activity.BaseMVPCompatActivity;
import com.hengjun.kingstar.sdk.utils.APKVersionCodeUtils;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.UpdateServiceAdapter;
import com.sc.VenusQueryBeta.adapter.VerSionInfoAdapter;
import com.sc.VenusQueryBeta.contract.about.AboutContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.AboutVGSBean;
import com.sc.VenusQueryBeta.presenter.about.AboutPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 *
 */
public class AboutKingStarActivity extends BaseMVPCompatActivity<AboutContract.AboutPresenter> implements AboutContract.IAboutView {
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;

    @BindView(R.id.about_kingstar_back)
    ImageButton aboutKingstarBack;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.about_kingstar_infornation)
    AppBarLayout aboutKingstarInfornation;
    @BindView(R.id.imageView4)
    ImageView imageView4;
    @BindView(R.id.textView4)
    TextView textView4;
    @BindView(R.id.updata)
    TextView updata;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.textView3)
    TextView textView3;

    private Dialog mDownloadDialog;
    private ProgressBar mProgress;
    private TextView schedule;
    private boolean cancelUpdate = false;
    private AboutKingStarActivity.downloadApkThread downloadApkThread;
    private PopupWindow popupWindow;
    private TextView tv_versionName;
    private Button btn_update;
    private Button btn_update_cancel;
    private VerSionInfoAdapter verSionInfoAdapter;
    //    private UpdateServiceAdapter updateServiceAdapter;
    private RecyclerView rv_update_info;
    private AlertView mCallView;
    private View contentView;
    private int item;
    private WebView webView;
    private TextView mpercentage;

    @Override
    protected void initView(Bundle savedInstanceState) {
        textView4.setText(APKVersionCodeUtils.getVerName(AboutKingStarActivity.this));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_about_king_star;
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return AboutPresenter.newInstance();
    }

    @Override
    protected void initData() {
        super.initData();
    }


    @Override
    public void showAboutVGSDataSuccess(AboutVGSBean aboutVGSBean) {
        LogUtils.e("当前" + aboutVGSBean.getList().size());

        hideProgressDialog();
        LogUtils.e("后台参数" + APKVersionCodeUtils.getVerName(AboutKingStarActivity.this) + aboutVGSBean.getTotalByte() + "     " + aboutVGSBean.getUrl() + "      " + aboutVGSBean.getVer() + "   size=  ");
        if (APKVersionCodeUtils.getVerName(AboutKingStarActivity.this).equals(aboutVGSBean.getVer())) {//当前版本一样
            ToastUtils.showToast("当前已经是最新版本！");
        } else {
//                  update(aboutSKBean.getVer(),aboutSKBean);
            inputOtherPwdWindow(aboutVGSBean);
        }
    }

    @Override
    public void showNetworkError(Throwable throwable) {
        LogUtils.e("error" + throwable.getMessage());
        hideProgressDialog();
    }

    @Override
    public void showUpdateMsg(Object o) {

    }


    @OnClick({R.id.about_kingstar_back, R.id.updata})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.about_kingstar_back:
                finish();
                break;
            case R.id.updata:
                long l = System.currentTimeMillis();
                long l1 = (long) 10000000000.0;
                showProgressDialog(getString(R.string.now_check));
                for (int i = 0; i < 10; i++) {
                    item = (int) ((Math.random() * 9 + i) * 1000000000);
                }
                LogUtils.e("生成的随机数" + l + "==" + l % l1);
                mPresenter.aboutVGS(l % l1);
                break;
        }
    }

    /**
     * 弹出窗口
     *
     * @param aboutVGSBean
     */
    @SuppressLint("WrongConstant")
    private void inputOtherPwdWindow(final AboutVGSBean aboutVGSBean) {
        contentView = LayoutInflater.from(this).inflate(R.layout.custom_version_update, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                if (webView != null) {
                    webView.clearCache(true);
                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        //这句话，让pop覆盖在输入法上面
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);//设置弹出动画

//
        tv_versionName = contentView.findViewById(R.id.tv_versionName);//版本名稱
        webView = contentView.findViewById(R.id.webView);//版本名稱
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//设置wenview不缓存数据
        tv_versionName.setText(aboutVGSBean.getVer());
        //更新信息
        rv_update_info = contentView.findViewById(R.id.rv_update_info);
        rv_update_info.setLayoutManager(new LinearLayoutManager(this));
        rv_update_info.setAdapter(new UpdateServiceAdapter(R.layout.layout_version_item, aboutVGSBean.getList()));
        btn_update = contentView.findViewById(R.id.btn_update);//更新

        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDownloadDialog(aboutVGSBean.getUrl());
                popupWindow.dismiss();


            }
        });

        btn_update_cancel = contentView.findViewById(R.id.btn_update_cancel);//取消更新


        btn_update_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        // 5 在底部显示
        popupWindow.showAtLocation(contentView.findViewById(R.id.rl_custom),
                Gravity.CENTER, 0, 0);

        webView.loadUrl("http://home.myvip18.com:8080/UpdateWizardServer/sanchuanAndroidApp/VenusQueryBeta/update/updateReadMe.html");
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog(String url) {
        // 构造软件下载对话框
        mDownloadDialog = new Dialog(AboutKingStarActivity.this, R.style.MyDialogStyle);
        mDownloadDialog.setContentView(R.layout.download_dialog);
        mProgress = (ProgressBar) mDownloadDialog.findViewById(R.id.progressBar1);
        mpercentage = mDownloadDialog.findViewById(R.id.tv_percentage);
        Button exit = (Button) mDownloadDialog.findViewById(R.id.button1);
//        schedule = (TextView) mDownloadDialog.findViewById(R.id.textView2);
        exit.setOnClickListener(new View.OnClickListener() {//点击进度条取消更新

            @Override
            public void onClick(View v) {
                mDownloadDialog.dismiss();
                cancelUpdate = true;
                finish();
            }
        });
        mDownloadDialog.show();
        // 下載文件
        downloadApk(url);
    }

    /**
     * 下载apk文件
     *
     * @param url
     */
    private void downloadApk(String url) {
        // 启动新线程下载软件
//        new downloadApkThread(url).start();
        requestPermissions(url);
    }

    private void requestPermissions(final String url) {
        RxPermissions rxPermission = new RxPermissions(this);
        //请求权限全部结果
        rxPermission.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (!granted) {
                            ToastUtils.showToast(getString(R.string.app_not_jurisdiction));
                            // 取消下载对话框显示
                            mDownloadDialog.dismiss();
                            popupWindow.dismiss();
                        } else {
                            // 启动新线程下载软件
                            downloadApkThread = new downloadApkThread("http://home.myvip18.com:8080/UpdateWizardServer/sanchuanAndroidApp/VenusQueryBeta/update/VenusQueryBeta.apk");
                            downloadApkThread.start();
                        }

                    }
                });
    }

    /**
     * 下载文件线程  需要动态权限
     */
    public class downloadApkThread extends Thread {
        private String murl;

        public downloadApkThread(String url) {
            this.murl = url;
        }

        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory()
                            + "/";
                    mSavePath = sdpath + "SKQUERY";

                    URL url = new URL(murl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "VenusQueryBeta.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        LogUtils.e("progress==" + progress);
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 101);
                        LogUtils.e("progress==" + progress);
                        // 更新进度
                        mHandler.sendEmptyMessage(1);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(2);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);
                    {
                        LogUtils.e("MalformedURLExgdgdgdgdgdg5498654189ception==");
                    }
                    fos.close();
                    is.close();
                } else {
                    LogUtils.e("MalformedURLExgdgdgdgdgdg5498654189ception==");
                }
            } catch (MalformedURLException e) {
                LogUtils.e("MalformedURLException==" + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                LogUtils.e("IOException==" + e.getMessage());
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, "VenusQueryBeta.apk");
        LogUtils.e("mSavePath===" + mSavePath);
        if (apkfile.exists()) {
            Intent intent = new Intent();
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//加这几话
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                LogUtils.e(apkfile.toString());
                uri = FileProvider.getUriForFile(getApplicationContext(), "com.sc.VenusQueryBeta.fileProvider", apkfile);
            } else {
                uri = Uri.fromFile(apkfile);
            }
            intent.setDataAndType(uri,
                    "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            mHandler.sendEmptyMessage(3);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case 1:
                    // 设置进度条位置
                    LogUtil.e("progress="+progress);
                    LogUtil.e("R.string.down_progress + String.valueOf(progress)="+R.string.down_progress + String.valueOf(progress) + "%");
                    mProgress.setProgress(progress);
                    mpercentage.setText(getResources().getString(R.string.down_progress)+
                            String.valueOf(progress)+ "%");
                    break;
                case 2:
                    // 安装文件
                    installApk();
                    break;
                case 3:
                    Toast.makeText(mContext, R.string.soft_update_noIn,
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.clearCache(true);
        }
    }
}
